﻿using System.Collections.Generic;
using System.Linq;
using SharePoint.Security.ConfigAnalyzer.Engine.Base;
using SharePoint.Security.ConfigAnalyzer.Engine.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using RuleInfo = SharePoint.Security.ConfigAnalyzer.Engine.Common.RuleInfo;
using System.Configuration;
using System;

namespace SharePoint.Security.ConfigAnalyzer.Engine.Rules.SearchAdmin
{
    class FarmAdminAccounts : BaseRule
    {
        #region Overrides of BaseRule

        string idealFarmAdminCount = null;
        int intFarmAdminCount = 0;

        public FarmAdminAccounts()
        {
            idealFarmAdminCount = ConfigurationSettings.AppSettings["IdealFarmAdminCount"];

            if (idealFarmAdminCount != null)
            {
                intFarmAdminCount = Convert.ToInt16(idealFarmAdminCount);
            }
            RuleInfo = new RuleInfo
            {
                Description = "Ensure application uses the lowest number of Farm Administrators",
                Title = "Farm Admin Accounts",
                ExpectedValue = string.Format("< {0}", (intFarmAdminCount + 1).ToString())
            };
        }

        public override void Validate()
        {
            int farmAdminCount = 0;
            List<SPUser> farmAdminList = new List<SPUser>();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPGroup adminGroup = SPAdministrationWebApplication.Local.Sites[0].AllWebs[0].SiteGroups["Farm Administrators"];

                foreach (SPUser spUser in adminGroup.Users)
                {
                    farmAdminList.Add(spUser);
                }

                farmAdminCount = farmAdminList.Count();
            });



            if (farmAdminCount <= intFarmAdminCount && farmAdminCount > 0) //Read this from Config File
            {
                Status = Status.Pass;
            }
            else
            {
                Status = Status.Fail;
            }

            CurrentValue = farmAdminCount.ToString();
        }

        #endregion
    }
}
